//  https://www.luogu.com.cn/problem/P1379

#include<iostream>
#include<unordered_map>
#include<queue>
using namespace std;

int dx[] = { 0,0,1,-1 };
int dy[] = { 1,-1,0,0 };
string s;
string aim = "123804765";
unordered_map<string, int> dist;

void bfs()
{
    queue<string> q;
    q.push(s);
    dist[s] = 0;

    while (q.size())
    {
        auto t = q.front();q.pop();
        int pos = 0;
        while (t[pos] != '0') pos++;
        int x = pos / 3, y = pos % 3;
        for (int k = 0;k < 4;k++)
        {
            int i = x + dx[k], j = y + dy[k];
            if (i >= 0 && i <= 2 && j >= 0 && j <= 2)
            {
                string next = t;
                int p = 3 * i + j;
                swap(next[p], next[pos]);
                if (dist.count(next)) continue;

                dist[next] = dist[t] + 1;
                q.push(next);

                if (next == aim) return;
            }
        }
    }
}
int main()
{
    cin >> s;
    bfs();
    cout << dist[aim] << endl;
    return 0;
}